import requests
import time
import pymysql
import csv


def main():
    # 获取各城市code
    with open('city_code.csv', 'r') as f:
        data = csv.reader(f)
        for i in data:
            if i:
                city_code.append(i)

    for i in city_code:
        city_weather(i)
        time.sleep(0.6)


def city_weather(city):
    total_url = url + city[0]
    # 获取网页请求
    try:
        resp = requests.get(total_url, headers=headers)
    except requests.exceptions.ConnectionError:
        print('ERROR，网络连接错误！！！')
        print(city[1], '数据获取失败')
        return
    data = resp.json()

    # 判断是否存在该城市的天气数据
    status = data['data']['result']
    if status == 'false':
        print(city[1], '数据获取失败')
        return

    li = []
    data2 = data['data']['data']
    for i in data2:
        data3 = i['forecast_data']
        date = i['forecast_date']
        for j in data3:
            daynight = '昼' if j['daynight'] == 0 else '夜'
            li2 = (date, daynight, j['weather_name'], j['min_temp'], j['max_temp'], j['wind_power_desc'], j['wind_direction_desc'])
            li.append(li2)

    weather_data[city[1]] = li
    print(li)


if __name__ == '__main__':
    start = time.time()
    url = 'https://www.amap.com/service/weather?adcode='
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/90.0.4430.72 Safari/537.36',
    }
    city_code = []
    weather_data = {}
    main()
    print(len(weather_data))
    with open('temp_weather.txt', 'w') as f:
        f.write(str(weather_data))

    print('总用时：', time.time()-start)


